package server;

import common.MessageID;
import online.chazi.netkit.NetkitContext;
import online.chazi.netkit.Session;
import online.chazi.netkit.SessionGroup;
import online.chazi.netkit.messaging.Message;

import java.util.Collection;

/**
 * 说明：作者很懒，什么都没留下
 * Created by 叉子同学 on 2020-04-24 15:55
 */
public class SessionHolder {

    private static final NetkitContext CONTEXT = new NetkitContext(4);

    //保存所有用户的session
    private static final SessionGroup ALL_USER_SESSIONS = new SessionGroup();

    // 保存系统session
    private static final SessionGroup ALL_SYSTEM_SESSIONS = new SessionGroup();

    public static NetkitContext getContext() {
        return CONTEXT;
    }

    public static void addUserSession(int userId, Session session) {
        // 判断是否有已经在线的session,挤下线
        Session s = getUserSession(userId);
        if (s != null) {
            Message logoutMessage = new Message(MessageID.LOGOUT.id);
            s.sendMessageAndClose(logoutMessage);
            removeUserSession(userId);
        }
        ALL_USER_SESSIONS.add(userId, session);
    }

    public static Session getUserSession(int userId) {
        return ALL_USER_SESSIONS.get(userId);
    }

    public static void removeUserSession(int userId) {
        ALL_USER_SESSIONS.remove(userId);
    }

    public static Collection<Session> getAllUserSession() {
        return ALL_USER_SESSIONS.sessions();
    }

    // 系统session相关的方法

    public static void addSystemSession(int systemId, Session session) {
        // 判断是否有已经在线的session,挤下线
        Session s = getSystemSession(systemId);
        if (s != null) {
            Message logoutMessage = new Message(MessageID.CLOSE.id);
            s.sendMessageAndClose(logoutMessage);
            removeSystemSession(systemId);
        }
        ALL_SYSTEM_SESSIONS.add(systemId, session);
    }

    public static Session getSystemSession(int systemId) {
        return ALL_SYSTEM_SESSIONS.get(systemId);
    }

    public static void removeSystemSession(int systemId) {
        ALL_SYSTEM_SESSIONS.remove(systemId);
    }
}
